package org.spring.blog.dao;

import org.spring.blog.pojo.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

public interface UserDao extends JpaRepository<User, String>, JpaSpecificationExecutor<User> {

    /**
     * 根据用户名查找用户
     *
     * @param userName 用户名
     * @return 用户对象
     */
    User findOneByUserName(String userName);

    /**
     * 根据用户邮箱查找用户
     *
     * @param email 邮箱
     * @return 用户对象
     */
    User findOneByEmail(String email);

    /**
     * 根据id查找用户
     *
     * @param _id 用户id
     * @return 用户对象
     */
    User findOneById(String _id);

    /**
     * 封禁用户
     *
     * @param state 用户状态
     * @return 修改条数
     */
    @Modifying
    @Query(nativeQuery = true, value = "update sob_blog_system.tb_user set sob_blog_system.tb_user.state = ?1 where sob_blog_system.tb_user.id = ?2")
    int updateUserStateById(String state, String userId);

    @Query(value = "select new User(u.id,u.userName,u.roles,u.avatar,u.email,u.sign,u.state,u.regIp, u.loginIp, u.createTime, u.updateTime) from User as u")
    Page<User> listAllUserNoPassword(Pageable _pageable);


    @Modifying
    @Query(nativeQuery = true, value = "update sob_blog_system.tb_user set sob_blog_system.tb_user.password = ?1 where sob_blog_system.tb_user.email = ?2")
    int updatePasswordByEmail(String _encode, String _email);

    @Modifying
    @Query(nativeQuery = true, value = "update sob_blog_system.tb_user set sob_blog_system.tb_user.email = ?1 where sob_blog_system.tb_user.id = ?2")
    int updateEmailById(String _email, String _id);
}
